#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import re
import pycurl
import StringIO

import FileHostProtoType


class ebuitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
        if not link:
            self.link = "http://www.embedupload.com/?d=%s" % self.id
    
class embedupload(FileHostProtoType.FileHostProcess):            
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "EmbedUpload" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.mirrors = {'RS': 'Rapidshare',
                        'MF': 'Mediafire',
                        'HF': 'Hotfile',
                        'FF': 'Filefactory',
                        'DF': 'Depositfiles',
                        '2S': '2shared',
                        'FS': 'Fileserve',
                        'WU': 'Wupload',
                        '4S': '4shared',
                        'FO': 'Filesonic',
                        'MU': 'Megaupload'
                        }
            
    def login(self):
        if self.islogin:
            return True
        #build opener
        self.generateOpener()
        print >> self.fherr, 'Embedupload is no need to login.'
        self.islogin = True
        return True
    
    def get_mirror_url(self, em_mirror_url):
        p = pycurl.Curl() 
        p.setopt(pycurl.URL, em_mirror_url)
        response = StringIO.StringIO()
        p.setopt(pycurl.WRITEFUNCTION, response.write)
        try:
            p.perform()
        except:
            self.fherr.write("failed to access %s" % em_mirror_url)		
            return ''
        return p.getinfo(pycurl.REDIRECT_URL) 
    
    def find(self, filenames = [], filelist = None):
        found = []
        if filelist == None:
            return found      
        filelistlower = [fl.name.lower() for fl in filelist]
        todel = []
        for fl in filenames:
            try:
                index = filelistlower.index(os.path.basename(fl).lower())
                found.append(filelist[index])
                todel.append(fl)
            except:
                continue
        for d in todel:
            filenames.remove(d)
        found.sort()
        return found
        
    def getFileList(self):
        return []
    
    def upload_web(self, file, progressLog=None, other_args=None):
        #indexpage
        #print "other_args in upload():"
        #print other_args
        selected_mirrors = []
        data = {'file_1':open(file, 'rb'),
                'site':'http://',
                'descripion':'',
                'email':'',
                'do':'upload'
                }
        if other_args:
            mirrors = other_args.get('message','')
            if mirrors:
                mirrors = mirrors.split(';')
                for m in mirrors:
                    tokens = m.split(':')
                    m_host = tokens[0].upper()
                    m_host = self.mirrors.get(m_host, '')
                    if m_host:
                        data[m_host] = '1'
                        selected_mirrors.append(tokens[0].upper())
                    if len(tokens) == 3:
                        data[m_host+"_login_username"]=tokens[1]
                        data[m_host+"_login_password"]=tokens[2]
                        
        get_upload_info_url = 'http://www.embedupload.com/lib/GenerateUnqidAndAction.php?_=%s' %\
                                      self.get_timeticket(13)
        get_upload_info_page = self.post_request(get_upload_info_url).encode('utf8','ignore')
        
        lines = get_upload_info_page.split('\n')
        
        server_token = lines[0].split("'")
        server = server_token[1]
        path_token = lines[1].split("'")
        path = path_token[1]
        id_token = lines[2].split('"')
        id = id_token[1]
        
        upload_link = "%s%s?upload_id=%s" % (server, path, id)
        #print data
        #print upload_link
        
        self.fherr.write("Uploading...%s" % file)
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_file(upload_link, data, self.get_cookies(), callback=callback)
        #result
        if not 'success' in result:
            self.fherr.write(result)
            self.fherr.write("orz:" + upload_link)
            self.fherr.write("Failed to upload %s" % file)
            time.sleep(300)
            return

        startpos = result.find('success <br> ')
        endpos = result.find('</div>',startpos)
        code = result[startpos+13:endpos]
        link = 'http://www.embedupload.com/?d=%s' % code
        item = ebuitem(os.path.basename(file), 'file', code, '', self.rename_func(file))
        self.newupload.append(item)
        self.fhout.write(item.format()) 
        self.fherr.write("yeh:" + upload_link)
        return item
        interval = 60
        time.sleep(interval)
        times = (self.wait_time-interval)/interval-1
        while times > 0:
            pending = self.post_request(link)
            if not "pending" in pending:
                break  
            self.fherr.write("waiting for pending...")
            time.sleep(interval)
            times -= 1 
            
        for m in selected_mirrors:
            em_mirror_url = 'http://www.embedupload.com/?%s=%s' % (m,code)
            while times > 0:
                self.fherr.write("fetching..." + em_mirror_url)
                mirror_url = self.get_mirror_url(em_mirror_url)            
                if mirror_url:
                    m_item = ebuitem(os.path.basename(file), 'file', code, mirror_url, self.rename_func(file))
                    self.newupload.append(m_item)
                    self.fhout.write(m_item.format()) 
                    break
                time.sleep(interval)
                times -= 1 
        return item